<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input :placeholder="$t('table.id')" v-model="listQuery.id" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>

      <el-input :placeholder="$t('table.mobile')" v-model="listQuery.mobile" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>


      <el-select v-model="listQuery.isVip" :placeholder="$t('table.vip')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="isVip in isVips" :key="isVip" :label="isVip" :value="isVip"/>
      </el-select>


      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="delList">{{ $t('table.del') }}</el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('table.export') }}</el-button>
    </div>


    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.nickname')" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.mobile')" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mobile }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.openid')" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.openid }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.vip')" align="center" width="90px">
        <template slot-scope="scope">
          <span class="link-type">
            {{ scope.row.isVip === 1 ? '是' : '否' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.date')" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>


      <el-table-column :label="$t('table.status')" class-name="status-col" width="100">
        <template slot-scope="scope">

          <el-tag :type="scope.row.isFreeze | statusFilter">{{ scope.row.isFreeze === 0 ? '正常':'冻结' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" width="335px" class-name="small-padding fixed-width">
        <template slot-scope="scope">


          <el-button v-if="scope.row.isFreeze===1" size="mini" type="success" @click="thaw(scope.row,'published')">{{
            $t('table.thaw') }}
          </el-button>
          <el-button v-else type="warning" size="mini" @click="freeze(scope.row,'draft')">{{ $t('table.freeze') }}
          </el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger"
                     @click="delteWorker(scope.row.id)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>





  </div>
</template>

<script>
  import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
  import waves from '@/directive/waves' // Waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import { workerList } from '@/api/worker'
  import { freezeWorker } from '@/api/worker'
  import { thawWorker } from '@/api/worker'
  import { delWorker } from '@/api/worker'
  import { updateForm } from '@/api/worker'

  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: 'success',
          1: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10
        },
        isVips: [0, 1],
        textMap: {
          update: 'Edit',
          create: 'Create'
        },

        downloadLoading: false
      }
    },
    created() {
      //获取信息
      this.getList()
      //获取路径中的id
      this.getWorkerId()

    },


    methods: {
      //逻辑删除
      delteWorker(id){
        //删除操作
        this.$confirm('此操作注销该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          delWorker(id).then(result => {
            this.$message({
              type: 'success',
              message: '注销成功'
            })
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消注销'
          })
        })


      },
      //获取路径中的id
      getWorkerId(){
        if (this.$route.query.id){
          this.listQuery.id = this.$route.query.id
        };
      },
      //清空列表
      delList(){
        this.listQuery.id='',
        this.listQuery.mobile='',
        this.listQuery.isVip='',
        this.getList()
      },
      //查询列表
      getList() {
        this.listLoading = true
        workerList(this.listQuery).then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total


          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },


      //冻结分理员
      freeze(row, status) {
        // 冻结提示

        this.$confirm('此操作将冻结该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          freezeWorker(row.id).then(result => {

            this.$message({
              message: '冻结成功',
              type: 'success'
            })
            row.status = status
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消冻结'
          })
        })
      },
      //解冻分理员
      thaw(row, status) {

        thawWorker(row.id).then(result => {
          this.$message({
            message: '解冻成功',
            type: 'success'
          })
          row.status = status
          updateForm(this.$route.query.id).then(res =>{
            this.$message({
              message: '申诉已经处理',
              type: 'success'
            })
          } )
          this.getList()
        })

      },

     // 排序
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },

      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },

      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },

      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['ID', 'NiceName', 'Mobile', 'Openid', 'Vip', 'Date', 'Status']
          const filterVal = ['id','nickname', 'mobile', 'openid', 'isVip', 'creationTime', 'isFreeze']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'worker-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
